package com.dhcc.DRGsHosp.application.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.inject.Named;

import org.dayatang.domain.EntityRepository;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.JdbcTemplateObj;
import org.dayatang.querychannel.QueryChannelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.dhcc.DRGsHosp.application.PayGroupApplication;
import com.dhcc.DRGsHosp.core.domain.IndexCal;
import com.dhcc.DRGsHosp.infra.util.DrgsIndex;


@Named
@Transactional
public class PayGroupApplicationImpl implements PayGroupApplication {
	
	private QueryChannelService queryChannel;
	
	@Autowired
	private JdbcTemplateObj jdbcTemplateObj;
	@Autowired
	private NamedParameterJdbcTemplate jdbcTempSeverice;
	
	private static final Logger logger = LoggerFactory.getLogger(PayGroupApplicationImpl.class);
	
    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
    private EntityRepository repository;
    
    private EntityRepository getRepository() {
		if (repository == null) {
			repository = InstanceFactory.getInstance(
					EntityRepository.class, "repository");
		}
		return repository;
	}
    
    /**
     *  执行查询SQL
     *  @Description：
     *  @Author ChenHanlin  
     *  @see com.dhcc.DRGsHosp.application.impl.PayGroupApplication#findFeeExtremal()
     */
	@Override
	public List<Map<String, Object>> executeQueryForList(String sql,Object obj) {
		SqlParameterSource paramSource = new BeanPropertySqlParameterSource(obj);
		List<Map<String, Object>> mapLsit = new ArrayList<>() ;
		try {
			mapLsit = jdbcTempSeverice.queryForList(sql, paramSource) ;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(sql);
		}
		return mapLsit;
	}
	
	/**
	 * 执行更新SQL
	 *  @Description：
	 *  @Author ChenHanlin  
	 *  @see com.dhcc.DRGsHosp.application.PayGroupApplication#executeUpdate(java.lang.String, java.util.Map)
	 */
	@Override
	public int executeUpdate(String sql, Map<String, Object> condition) {
		return jdbcTempSeverice.update(sql, condition) ;
	}
	
	/**
	 * 
	 *  @Description：根据条件查询，正态分布的参数（均值和标准差）
	 *  @Author WENYI  
	 *  @see com.dhcc.DRGsHosp.application.PayGroupApplication#getNormalParamData(com.dhcc.DRGsHosp.core.domain.IndexCal, java.lang.String)
	 */
	@Override
	@Cacheable(value = "drgscom3.1.1", key = "'getNormalParamData' + #dto.pardepCode +  "
			+ "#dto.dateFrom + #dto.dateTo +  #dto.pardrgCode + #normalParam")
	public Map<String, Object> getNormalParamData(IndexCal dto, String normalParam){
		String sql = "SELECT ROUND(AVG(P00800000),2) AVG,ROUND(STDDEV(P00800000),2) STD FROM DRGS.MR_BASEINFO A LEFT JOIN DRGS.MR_IPINFO INFO ON A.PMAININDEX = INFO.PMAININDEX  \n "
				+ " LEFT JOIN DRGS.T_PATIENTDRG PDG ON INFO.PMAININDEX=PDG.PARID  \n "
				+ " LEFT JOIN DRGS.T_MEDINS MEDINS ON MEDINS.PARID = INFO.PMAININDEX  \n "
				+ " WHERE P00800000 IS NOT NULL  \n ";
		if(StringUtils.hasLength(dto.getPardepCode())){
			sql+="AND  P00300001='"+dto.getPardepCode()+"' \n";
		}
		if(StringUtils.hasLength(dto.getPardrgCode())){
			sql+="AND  PARDRG_CODE='"+dto.getPardrgCode()+"' \n";
		}
		//***医院编码***
		if(StringUtils.hasLength(dto.getHospCode())){
			sql+="AND  instr('"+dto.getHospCode()+"',a.p00010001)>0 \n";
		}
		//***医保条件***
		if("1".equals(dto.getpType())){
			sql+="AND  medins.parid is not null  \n";
		}
		//正态分布参数为本期 或 正态分布参数为累计值且监测时间类型为MC  查询本期
		if("T".equals(normalParam)||("A".equals(normalParam)&&"MC".equals(dto.getMrType()))){
			sql+="AND TO_CHAR(P00290000,'yyyy-mm-dd') BETWEEN '"+dto.getDateFrom()+"' AND '"+dto.getDateTo()+"' \n";
		}
		//正态分布参数为历史值，查询当年
		else if("H".equals(normalParam)){
			sql+="AND TO_CHAR(P00290000,'yyyy') = '"+dto.getDateFrom().substring(0, 4)+"' \n";
		}
		//正态分布参数为累计值，监测时间类型为M 如2017-07 查询时间范围为2017-01-01 - 2017-07-31
		else if("A".equals(normalParam)&&"M".equals(dto.getMrType())){
			sql+="AND TO_CHAR(P00290000,'yyyy-mm-dd') BETWEEN '"+dto.getDateFrom().substring(0, 4)+"01-01' AND '"+dto.getDateTo()+"' \n";
		}
		Map<String, Object> mrList = jdbcTemplateObj.queryForMap(sql);
		return mrList;
	}
	/**
	 * 
	 *  @Description：查询病例数据
	 *  @Author WENYI  
	 *  @see com.dhcc.DRGsHosp.application.PayGroupApplication#getNormalCaseData(com.dhcc.DRGsHosp.core.domain.IndexCal)
	 */
	@Override
	@Cacheable(value = "drgscom3.1.1", key = "'getNormalCaseData' + #dto.pardepCode +  "
			+ "#dto.dateFrom + #dto.dateTo +  #dto.pardrgCode")
	public List<Object[]> getNormalCaseData(IndexCal dto){
		String sql = "SELECT P00800000,P00300001,P00300000   FROM DRGS.MR_BASEINFO A LEFT JOIN DRGS.MR_IPINFO INFO ON A.PMAININDEX = INFO.PMAININDEX \n "
				+ " LEFT JOIN DRGS.T_PATIENTDRG PDG ON INFO.PMAININDEX=PDG.PARID  \n "
				+ " LEFT JOIN DRGS.T_MEDINS MEDINS ON MEDINS.PARID = INFO.PMAININDEX  \n "
				+ " WHERE P00800000 IS NOT NULL  AND TO_CHAR(P00290000,'yyyy-mm-dd') BETWEEN '"+dto.getDateFrom()+"' AND '"+dto.getDateTo()+"' \n ";
		if(StringUtils.hasLength(dto.getPardepCode())){
			sql+="AND P00300001='"+dto.getPardepCode()+"' \n";
		}
		if(StringUtils.hasLength(dto.getPardrgCode())){
			sql+="AND PARDRG_CODE='"+dto.getPardrgCode()+"' \n";
		}
		//***医院编码***
		if(StringUtils.hasLength(dto.getHospCode())){
			sql+="AND  instr('"+dto.getHospCode()+"',a.p00010001)>0 \n";
		}
		//***医保条件***
		if("1".equals(dto.getpType())){
			sql+="AND  medins.parid is not null  \n";
		}
		sql+="ORDER BY P00800000 \n";
		List<Object[]> mrList = getQueryChannelService().createSqlQuery(sql.toString()).list();
		return mrList;
	}

}
